import tensorflow as tf
import matplotlib.pyplot as plt
import ssl
import numpy as np

ssl._create_default_https_context = ssl._create_unverified_context
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0

x_train = tf.reshape(x_train, [-1, 28, 28, 1])
y_train = tf.reshape(y_train, [-1, 1])
# x_train = x_train.reshape(-1, 28, 28, 1).astype(np.float32)

# plt.figure()
# plt.imshow(x_train[0], cmap='gray')
# plt.grid(False)
# plt.show()
dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
# print(dataset.output_types)
# print(dataset.output_shapes)
dataset = dataset.batch(50).repeat()
iterator = dataset.make_one_shot_iterator()
image, label = iterator.get_next()

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2), (1, 1), 'same'))
model.add(tf.keras.layers.Conv2D(64, (5, 5), (1, 1), 'same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2), (1, 1), 'same'))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1024, activation=tf.nn.relu))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

model.compile(optimizer=tf.train.AdamOptimizer(0.0001),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(image, label, epochs=2, steps_per_epoch=120)
# model.fit(dataset, epochs=2, steps_per_epoch=120)
# model.fit(x_train, y_train, batch_size=50, epochs=2)
